import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { useAppStore } from '@/store/app'

// Import views
const Login = () => import('@/views/Login.vue')
const Layout = () => import('@/components/Layout.vue')
const Chat = () => import('@/views/chat/index.vue')
const History = () => import('@/views/History.vue')
const Settings = () => import('@/views/Settings.vue')
const SQLLog = () => import('@/views/SQLLogNew.vue')
const DynamicTable = () => import('@/views/DynamicTable.vue')
const ApiDocs = () => import('@/views/ApiDocs.vue')
const NotFound = () => import('@/views/NotFound.vue')

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      requiresAuth: false,
      title: '登录',
      hideInMenu: true
    }
  },
  {
    path: '/',
    component: Layout,
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '',
        redirect: '/chat'
      },
      {
        path: 'chat',
        name: 'Chat',
        component: Chat,
        meta: {
          title: 'AI助手',
          icon: 'carbon:ai-label',
          permissions: ['chat:read', 'chat:write']
        }
      },
      {
        path: 'history',
        name: 'History',
        component: History,
        meta: {
          title: '对话历史',
          icon: 'carbon:database-messaging',
          permissions: ['chat:read']
        }
      },
      {
        path: 'sql-log',
        name: 'SQLLog',
        component: SQLLog,
        meta: {
          title: 'SQL日志',
          icon: 'carbon:sql',
          permissions: ['system:manage', 'sql:read']
        }
      },
      {
        path: 'dynamic-table',
        name: 'DynamicTable',
        component: DynamicTable,
        meta: {
          title: '动态表格',
          hideInMenu: true, // 隐藏在菜单中，通过动态菜单访问
          permissions: []
        }
      },
      {
        path: 'docs',
        name: 'ApiDocs',
        component: ApiDocs,
        meta: {
          title: '接口文档',
          icon: 'carbon:api',
          permissions: []
        }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: Settings,
        meta: {
          title: '设置',
          icon: 'carbon:settings',
          permissions: []
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
    meta: {
      title: '页面未找到',
      hideInMenu: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// Navigation guards
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  const appStore = useAppStore()
  
  if (import.meta.env.DEV) {
    console.log('Router beforeEach:', {
      to: to.path,
      authenticated: authStore.isAuthenticated,
      user: !!authStore.user,
      token: !!authStore.token
    })
  }

  // 如果有token但没有用户信息，说明还在初始化过程中，等待一下
  if (authStore.token && !authStore.user && !authStore.loading) {
    console.log('🔄 等待认证状态初始化完成...')
    try {
      await authStore.getCurrentUser()
    } catch (error) {
      console.error('认证初始化失败:', error)
    }
  }
  
  // Set loading state only for route changes that need it
  // Don't set loading if coming from login page or if already loading
  if (to.path !== '/login' && from.path !== '/login' && !appStore.loading) {
    appStore.setLoading(true)
  }
  
  // Clear any previous errors
  appStore.clearError()
  
  // Check if route requires authentication
  const requiresAuth = to.meta.requiresAuth !== false
  
  if (requiresAuth && !authStore.isAuthenticated) {
    // Not authenticated, redirect to login
    if (to.path !== '/login') {
      next({ name: 'Login', query: { redirect: to.fullPath } })
    } else {
      next()
    }
    return
  }
  
  if (to.name === 'Login' && authStore.isAuthenticated) {
    // Already authenticated, redirect to main app
    next({ path: '/' })
    return
  }
  
  // Check permissions if required
  if (requiresAuth && to.meta?.permissions && Array.isArray(to.meta.permissions)) {
    const permissions = to.meta.permissions as string[]
    const hasPermission = authStore.hasAnyPermission(permissions)
    
    if (import.meta.env.DEV) {
      console.log('Permission check:', {
        route: to.path,
        requiredPermissions: permissions,
        userPermissions: authStore.userPermissions,
        hasPermission: hasPermission
      })
    }
    
    if (permissions && permissions.length > 0 && !hasPermission) {
      appStore.showError('您没有访问此页面的权限')
      
      // 重定向到设置页面（无权限要求）
      next({ path: '/settings' })
      return
    }
  }
  
  next()
})

router.afterEach((to, _from) => {
  const appStore = useAppStore()
  
  // Update page title
  if (to.meta.title) {
    appStore.setPageTitle(to.meta.title as string)
  }
  
  // Update breadcrumbs
  const breadcrumbs: { name: string; path?: string }[] = []
  
  // Add parent routes to breadcrumbs
  const matched = to.matched.filter(record => record.meta.title)
  matched.forEach((record, index) => {
    if (record.meta.title) {
      breadcrumbs.push({
        name: record.meta.title as string,
        path: index === matched.length - 1 ? undefined : record.path
      })
    }
  })
  
  appStore.setBreadcrumbs(breadcrumbs)
  
  // Clear loading state
  appStore.setLoading(false)
  
  if (import.meta.env.DEV) {
    console.log('Router afterEach (after clearing loading):', {
      to: to.path,
      loading: appStore.loading
    })
  }
})

// Handle router errors
router.onError((error) => {
  const appStore = useAppStore()
  console.error('Router error:', error)
  appStore.handleError(error, 'Router Navigation')
})

export default router

// Export route helpers
export const getRoutesByPermissions = (permissions: string[]) => {
  return routes.filter(route => {
    if (route.children) {
      return route.children.some(child => 
        !child.meta?.permissions || 
        !Array.isArray(child.meta.permissions) ||
        child.meta.permissions.length === 0 ||
        child.meta.permissions.some((p: string) => permissions.includes(p))
      )
    }
    return !route.meta?.permissions || 
           !Array.isArray(route.meta.permissions) ||
           route.meta.permissions.length === 0 ||
           route.meta.permissions.some((p: string) => permissions.includes(p))
  })
}

export const getMenuRoutes = () => {
  const flattenRoutes = (routes: RouteRecordRaw[]): RouteRecordRaw[] => {
    let result: RouteRecordRaw[] = []
    
    routes.forEach(route => {
      if (!route.meta?.hideInMenu) {
        if (route.children) {
          result = result.concat(flattenRoutes(route.children))
        } else {
          result.push(route)
        }
      }
    })
    
    return result
  }
  
  return flattenRoutes(routes).filter(route => 
    route.meta?.title && !route.meta?.hideInMenu
  )
}
